package com.yuncheng.spcyApi.controller;

import java.io.File;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuncheng.spcyApi.alog.annotation.Log;
import com.yuncheng.spcyApi.constant.other.BhgzConstant;
import com.yuncheng.spcyApi.constant.common.BusinessConstant;
import com.yuncheng.spcyApi.constant.common.LogConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.entity.SpcySqsxBasic;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.spcyApi.service.ISpcyLogService;
import com.yuncheng.spcyApi.service.ISpcySqsxBaiscService;
import com.yuncheng.spcyApi.utils.*;
import com.yuncheng.vo.HttpResult;
import com.yuncheng.common.base.controller.BaseController;
import com.yuncheng.spcyApi.entity.SpcyRsBhgz;
import com.yuncheng.spcyApi.service.ISpcyRsBhgzService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.multipart.MultipartFile;
import utils.DateConversionUtils;
import utils.LogUtils;
import utils.ObjectToMapUtils;

/**
 * @Description: 审评查验-编号规则
 * @Author: csx
 * @Date: 2023-03-03
 * @Version: V1.0
 */
@Api(tags = "审评查验-编号规则接口")
@RestController
@RequestMapping("/api/spzx-spcy/spcyRsBhgz")
public class SpcyRsBhgzController extends BaseController<SpcyRsBhgz, ISpcyRsBhgzService> {

    private static final Logger log = LoggerFactory.getLogger(SpcyRsBhgzController.class);

    @Resource
    private ISpcyRsBhgzService spcyRsBhgzService;

    @Resource
    private ISpcyLogService spcyLogService;

    @Resource
    private ISpcySqsxBaiscService spcySqsxBaiscService;

    @Resource
    private LocalFileUploadUtils localFileUploadUtils;

    @Resource
    private MyExcelUtils myExcelUtils;

    /**
     * 分页列表查询
     *
     * @param spcyRsBhgz
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Log(title = "审评查验-编号规则-分页列表查询")
    @ApiOperation(value = "审评查验-编号规则-分页列表查询")
    @GetMapping(value = "/list")
    public HttpResult<?> queryPageList(SpcyRsBhgz spcyRsBhgz, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<SpcyRsBhgz> page = new Page<>(pageNo, pageSize);
        LambdaQueryWrapper<SpcyRsBhgz> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(spcyRsBhgz.getFywflcode()),SpcyRsBhgz::getFywflcode,spcyRsBhgz.getFywflcode());
        queryWrapper.like(StringUtils.isNotEmpty(spcyRsBhgz.getFtype1()),SpcyRsBhgz::getFtype1,spcyRsBhgz.getFtype1());
        queryWrapper.like(StringUtils.isNotEmpty(spcyRsBhgz.getFtype2()),SpcyRsBhgz::getFtype2,spcyRsBhgz.getFtype2());
        queryWrapper.like(StringUtils.isNotEmpty(spcyRsBhgz.getFtype3()),SpcyRsBhgz::getFtype3,spcyRsBhgz.getFtype3());
        queryWrapper.like(StringUtils.isNotEmpty(spcyRsBhgz.getFtype4()),SpcyRsBhgz::getFtype4,spcyRsBhgz.getFtype4());
        queryWrapper.like(StringUtils.isNotEmpty(spcyRsBhgz.getFqz()),SpcyRsBhgz::getFqz,spcyRsBhgz.getFqz());
        queryWrapper.like(StringUtils.isNotEmpty(spcyRsBhgz.getFhz()),SpcyRsBhgz::getFhz,spcyRsBhgz.getFhz());
        queryWrapper.like(StringUtils.isNotEmpty(spcyRsBhgz.getFlshws()),SpcyRsBhgz::getFlshws,spcyRsBhgz.getFlshws());

        queryWrapper.orderByAsc(SpcyRsBhgz::getCreateTime);
        IPage<SpcyRsBhgz> pageList = spcyRsBhgzService.page(page, queryWrapper);
        return HttpResult.ok(pageList);
    }



    /**
     * 添加
     *
     * @param spcyRsBhgz
     * @return
     */
    @Log(title = "审评查验-编号规则-添加")
    @ApiOperation(value = "审评查验-编号规则-添加")
    @PostMapping(value = "/add")
    public HttpResult<?> add(@RequestBody SpcyRsBhgz spcyRsBhgz) {
        spcyRsBhgzService.save(spcyRsBhgz);
        String operContent = "新增信息：";

        // 将map里面的属性和值转String
        Map<String, Object> beanMap = ObjectToMapUtils.objectToMap(spcyRsBhgz);
        operContent += LogUtils.MapToStringMethod(beanMap);
        spcyLogService.addLogs(LogConstant.LOGS_RS_BHGZ,operContent,spcyRsBhgz.getId(), LogConstant.LOGS_RS_BHGZ, SpcyConstant.LOGS_SYS_TYPE_XZ);
        return HttpResult.ok("添加成功");
    }

    /**
     * 编辑
     *
     * @return
     */
    @Log(title = "审评查验-编号规则-编辑")
    @ApiOperation(value = "审评查验-编号规则-编辑")
    @ApiImplicitParam(name = "id",value = "编号规则id",required = true)
    @PutMapping(value = "/edit")
    public HttpResult<?> edit(@RequestBody HashMap<String, String> buffer) throws InvocationTargetException, IllegalAccessException{
        if (StringUtils.isEmpty(buffer.get("id"))){
            return HttpResult.error("编号规则信息id不能为空");
        }
        String qyId = buffer.get("id");
        SpcyRsBhgz oldRsBhgz = spcyRsBhgzService.getById(qyId);
        SpcyRsBhgz oldRsBhgzUpdate = spcyRsBhgzService.getById(qyId);
        if (oldRsBhgz == null){
            return HttpResult.error("当前编号规则基本信息数据不存在，请重试");
        }
        ConvertUtils.register(new DateConvert(), java.util.Date.class);
        // 自动完成页面到bean的数据对接
        BeanUtils.populate(oldRsBhgzUpdate, buffer);
        spcyRsBhgzService.updateById(oldRsBhgzUpdate);

        String operContent = "基本信息修改：";
        Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(oldRsBhgz);
        operContent += LogUtils.BeanModifyMsg(oldRsBhgzUpdate,oldMap);

        spcyLogService.addLogs(LogConstant.LOGS_RS_BHGZ,operContent,qyId,LogConstant.LOGS_RS_BHGZ,SpcyConstant.LOGS_SYS_TYPE_XG);
        return HttpResult.ok("修改成功");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @Log(title = "审评查验-编号规则-通过id删除")
    @ApiOperation(value = "审评查验-编号规则-通过id删除")
    @DeleteMapping(value = "/delete")
    public HttpResult<?> delete(@RequestParam("id") String id) {
        if (StringUtils.isEmpty(id)){
            return HttpResult.error("id参数不能为空");
        }
        SpcyRsBhgz nowQy = spcyRsBhgzService.getById(id);
        if (nowQy == null){
            return HttpResult.error("当前编号规则信息数据不存在，请重试");
        }
        spcyRsBhgzService.removeById(id);
        String operContent = "删除信息：";
        Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(nowQy);
        operContent += LogUtils.MapToStringMethod(oldMap);
        spcyLogService.addLogs(LogConstant.LOGS_RS_BHGZ,operContent,id,LogConstant.LOGS_RS_BHGZ,SpcyConstant.LOGS_SYS_TYPE_SC);
        return HttpResult.ok("删除成功");
    }

    /**
     * 通过id批量删除
     *
     * @param ids
     * @return
     */
    @Log(title = "审评查验-编号规则-批量删除")
    @ApiOperation(value = "审评查验-编号规则-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public HttpResult<?> deleteBatch(@RequestParam("ids") String ids) {
        if (StringUtils.isEmpty(ids)){
            return HttpResult.error("ids参数不能为空");
        }
        List<String> idsList = Arrays.asList(ids.split(","));
        List<SpcyRsBhgz> spcyRsBhgzList = spcyRsBhgzService.listByIds(idsList);
        if (CollectionUtils.isEmpty(spcyRsBhgzList)){
            return HttpResult.error("数据不存在，请重试");
        }
        String operContent = "";
        for (SpcyRsBhgz rsBhgz : spcyRsBhgzList){
            String id = rsBhgz.getId();
            spcyRsBhgzService.removeById(id);
            operContent = "删除信息：";
            Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(rsBhgz);
            operContent += LogUtils.MapToStringMethod(oldMap);
            spcyLogService.addLogs(LogConstant.LOGS_RS_BHGZ,operContent,id,LogConstant.LOGS_RS_BHGZ,SpcyConstant.LOGS_SYS_TYPE_SC);
            operContent = "";
        }

        return HttpResult.ok("删除成功");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @Log(title = "审评查验-编号规则-通过id查询")
    @ApiOperation(value = "审评查验-编号规则-通过id查询")
    @GetMapping(value = "/queryById")
    public HttpResult<?> queryById(@RequestParam("id") String id) {
        SpcyRsBhgz spcyRsBhgz = spcyRsBhgzService.getById(id);
        return HttpResult.ok(spcyRsBhgz);
    }

    /**
     * 导入编号规则库数据-表格excel
     */
    @Log(title = "导入编号规则库数据-表格excel")
    @ApiOperation(value = "导入编号规则库数据-表格excel")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "file",value = "excel模板文件",required = true),
    })
    @PostMapping(value = "impRsBhgzData")
    public HttpResult<?> impRsBhgzData(@RequestParam("file") MultipartFile file,@RequestParam("fywflcode")String ywflCode){
        if (file.isEmpty()){
            return HttpResult.error("文件不存在");
        }

        //获取文件名
        String fileName = file.getOriginalFilename();
        //判断文件类型，这里我们只要xls文件
        if (fileName != null && !fileName.endsWith(".xls") && !fileName.endsWith(".xlsx"))
            return HttpResult.error(1, "请选择“xls”或“xlsx”文件");

        File fileUpload = localFileUploadUtils.uploadDempFile(file,fileName);
        // 获取导入的数据
        List<Map<String, Object>> mapsList = null;
        try {
            mapsList = myExcelUtils.paresExclToMapList(BusinessConstant.IMPORT_RS_BHGZ_XML, fileUpload);
        } catch (Exception e) {
            log.error("导入编号规则库数据出错-{}",e.getMessage());
        }
        if (CollectionUtils.isNotEmpty(mapsList) && mapsList.size() > 0) {
            for (Map map : mapsList) {
                SpcyRsBhgz bhgz = new SpcyRsBhgz();
                BeanUtil.copyProperties(map,bhgz);
                bhgz.setId(GetUuIdUtils.ReplaceUuId());
                bhgz.setFywflcode(ywflCode);
                spcyRsBhgzService.save(bhgz);
                String operContent = "新增导入信息：";
                Map<String, Object> bhgzMap = ObjectToMapUtils.objectToMap(bhgz);
                operContent += LogUtils.MapToStringMethod(bhgzMap);
                spcyLogService.addLogs(LogConstant.LOGS_RS_BHGZ,operContent,bhgz.getId(),LogConstant.LOGS_RS_BHGZ,SpcyConstant.LOGS_SYS_TYPE_XZ);
            }
        }
        fileUpload.delete();
        return HttpResult.ok("导入成功");
    }

    /**
     * 下载编号规则库-导入模板
     * @param response
     */
    @Log(title = "下载编号规则库-导入模板")
    @ApiOperation(value = "下载编号规则库-导入模板")
    @GetMapping("/downRsBhgzTemplate")
    public void downRsBhgzTemplate(HttpServletResponse response){
        try {
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode("bhgzImpTemplate.xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();
            myExcelUtils.buildImpModel(BusinessConstant.IMPORT_RS_BHGZ_XML, out);
        } catch (Exception e) {
            log.error("下载编号规则库模板错误-{}",e.getMessage());
        }
    }

    /**
     * 导出编号规则库数据-表格excel
     */
    @Log(title = "导出编号规则库数据-表格excel")
    @ApiOperation(value = "导出编号规则库数据-表格excel")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "ids",value = "编号规则库字符逗号分割",dataType = "String")
    })
    @GetMapping("/exportRsBhgzData")
    public void exportRsBhgzData(@RequestParam(value = "ids",defaultValue = "")String ids,
                                SpcyRsBhgz spcyRsBhgz,
                                HttpServletResponse response){
        try {
            String name = "exportRsBhgz";
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(name+".xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();

            List<String> IdsList = Arrays.asList(ids.split(","));
            List<Object> list = new ArrayList<>(); // 导出的数据
            // 多选导出
            if (StringUtils.isNotEmpty(ids)) {
                List<SpcyRsBhgz> rsBhgzList = spcyRsBhgzService.listByIds(IdsList);
                if (CollectionUtils.isNotEmpty(rsBhgzList)){
                    for (SpcyRsBhgz e : rsBhgzList){
                        list.add(e);
                    }
                }
            }else {
                LambdaQueryWrapper<SpcyRsBhgz> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(StringUtils.isNotBlank(spcyRsBhgz.getFywflcode()),SpcyRsBhgz::getFywflcode,spcyRsBhgz.getFywflcode());
                queryWrapper.like(StringUtils.isNotEmpty(spcyRsBhgz.getFtype1()),SpcyRsBhgz::getFtype1,spcyRsBhgz.getFtype1());
                queryWrapper.like(StringUtils.isNotEmpty(spcyRsBhgz.getFtype2()),SpcyRsBhgz::getFtype2,spcyRsBhgz.getFtype2());
                queryWrapper.like(StringUtils.isNotEmpty(spcyRsBhgz.getFtype3()),SpcyRsBhgz::getFtype3,spcyRsBhgz.getFtype3());
                queryWrapper.like(StringUtils.isNotEmpty(spcyRsBhgz.getFtype4()),SpcyRsBhgz::getFtype4,spcyRsBhgz.getFtype4());
                queryWrapper.like(StringUtils.isNotEmpty(spcyRsBhgz.getFqz()),SpcyRsBhgz::getFqz,spcyRsBhgz.getFqz());
                queryWrapper.like(StringUtils.isNotEmpty(spcyRsBhgz.getFhz()),SpcyRsBhgz::getFhz,spcyRsBhgz.getFhz());
                queryWrapper.like(StringUtils.isNotEmpty(spcyRsBhgz.getFlshws()),SpcyRsBhgz::getFlshws,spcyRsBhgz.getFlshws());
                List<SpcyRsBhgz> rsBhgzList = spcyRsBhgzService.list(queryWrapper);
                // 条件导出
                if (CollectionUtils.isNotEmpty(rsBhgzList)){
                    for (SpcyRsBhgz e : rsBhgzList){
                        list.add(e);
                    }
                }
            }
            myExcelUtils.outputListToExclFile(BusinessConstant.IMPORT_RS_BHGZ_XML,list,out); // 导出模板数据成excel
        } catch (Exception e) {
            log.error("导出编号规则库数据出错-{}",e.getMessage());
        }
    }

    /**
     * 自动受理编号-通过检查类型和申请事项id
     */
    @Log(title = "自动受理编号-通过检查类型和申请事项id")
    @ApiOperation(value = "自动受理编号-通过检查类型和申请事项id")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "fywflcode",value = "业务分类编码",required = true),
            @ApiImplicitParam(name = "fjclx",value = "检查类型",required = true),
    })
    @GetMapping(value = "/autoSlbhBySqsxId")
    public HttpResult<?> autoSlbhBySqsxId(@RequestParam(value = "fywflcode",defaultValue = "")String fywflcode,
                                          @RequestParam(value = "fjclx",defaultValue = "")String type,
                                          @RequestParam(value = "sqsxid",defaultValue = "")String sqsxid){
        Map map = new HashMap();

        if (StringUtils.isNotBlank(sqsxid)){
            fywflcode = spcySqsxBaiscService.getYwflCodeBySqsxId(sqsxid);
        }else {
            if (StringUtils.isBlank(fywflcode)) {
                return HttpResult.error("业务分类/事项参数为空,请联系管理员！");
            }
        }

        if (StringUtils.isEmpty(type)){
            return HttpResult.error("请选择检查类型");
        }

        String baseYwfl = fywflcode;
        if (baseYwfl.equals(SpcyConstant.YWFL_CODE_YPZCLC)){
            baseYwfl = SpcyConstant.YWFL_CODE_YPZC;
        }

        List<SpcyRsBhgz> bghzTypeList = spcyRsBhgzService.list(new LambdaQueryWrapper<SpcyRsBhgz>()
                .eq(SpcyRsBhgz::getFywflcode, baseYwfl)
                .eq(SpcyRsBhgz::getFtype1, type));

        if (CollectionUtils.isEmpty(bghzTypeList)){
            return HttpResult.ok("没有配置对应的检查类型，请先配制参数");
        }

        String returnReportNo = "";

        SpcyRsBhgz nowCheckType = bghzTypeList.get(0);
        int lshws = Integer.valueOf(nowCheckType.getFlshws()); // 流水号位数
        String qz = nowCheckType.getFqz(); // 前缀

        String nowYear = DateConversionUtils.DateToYear(new Date()); // 当前年份

        String qzReportNo = qz + nowYear; // 前缀+年份 编号

        // 按前缀+年份查询
        List<SpcySqsxBasic> reportList = spcySqsxBaiscService.list(new LambdaQueryWrapper<SpcySqsxBasic>()
                .eq(SpcySqsxBasic::getFywflcode, fywflcode)
                .eq(SpcySqsxBasic::getFhbsxzt,0)
                .likeRight(SpcySqsxBasic::getFslbh, qzReportNo)
                .isNotNull(SpcySqsxBasic::getFslbh));

        if (CollectionUtils.isNotEmpty(reportList)) { // 不为空
            // 获取报告编号
            List<String> reportNoList = new ArrayList<>(reportList.stream().map(SpcySqsxBasic::getFslbh).collect(Collectors.toList()));

            // 对报告编号排序
            List<String> DescReportNoList = reportNoList.stream().sorted(Collections.reverseOrder()).collect(Collectors.toList());

            String firstReportNo = DescReportNoList.get(0); // 取最大的一个值
            int length = firstReportNo.length();
            if (length>lshws){
                String substring = firstReportNo.substring(length - lshws);

                int jqs = Integer.valueOf(substring); // 截取处理的数
                int newhjqs = jqs + 1; // 对截取处理的数+1
                String newJqsStr = String.valueOf(newhjqs); // 新字符串转字符串
                int length1 = newJqsStr.length(); // 新字符串长度

                if (lshws>length1){ // 流水号数>新字符串长度
                    int j = lshws - length1;
                    String lws = "";
                    for (int n = 0; n<j; n++){
                        lws += "0";
                    }
                    returnReportNo = qzReportNo + lws + newhjqs;
                }else if (lshws == length1){ // 长度相等
                    returnReportNo = qzReportNo + newJqsStr;
                }
            }

        }else { // 为空
            String lwz = ""; // 0的个数
            for (int i = 1; i<lshws; i++){
                lwz += "0";
            }
            qzReportNo += lwz + "1";
            returnReportNo = qzReportNo;
        }

        map.put("fslbh",returnReportNo);
        return HttpResult.ok(map);
    }

    /**
     * 评定编号
     */
    @Log(title = "自动评定编号-通过业务分类")
    @ApiOperation(value = "自动评定编号-通过业务分类")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "fywflcode",value = "业务分类编码",required = true)
    })
    @GetMapping(value = "/autoPdbhBySqsxId")
    public HttpResult<?> autoPdbhBySqsxId(@RequestParam(value = "fywflcode",defaultValue = "")String fywflcode,
                                          @RequestParam(value = "sqsxid",defaultValue = "") String sqsxid){

        if (StringUtils.isNotBlank(sqsxid)){
            fywflcode = spcySqsxBaiscService.getYwflCodeBySqsxId(sqsxid);
        }else {
            if (StringUtils.isBlank(fywflcode)) {
                return HttpResult.error("业务分类/事项参数为空,请联系管理员！");
            }
        }


        Map map = new HashMap();

        String baseYwfl = fywflcode;
        if (baseYwfl.equals(SpcyConstant.YWFL_CODE_YPZCLC)){
            baseYwfl = SpcyConstant.YWFL_CODE_YPZC;
        }

        List<SpcyRsBhgz> bghzTypeList = spcyRsBhgzService.list(new LambdaQueryWrapper<SpcyRsBhgz>()
                .eq(SpcyRsBhgz::getFywflcode, baseYwfl)
                .eq(SpcyRsBhgz::getFtype1, BhgzConstant.PDBH));

        if (CollectionUtils.isEmpty(bghzTypeList)){
            return HttpResult.error("没有配置对应的检查类型，请先配制参数");
        }
        String returnReportNo = "";

        SpcyRsBhgz nowCheckType = bghzTypeList.get(0);
        int lshws = Integer.valueOf(nowCheckType.getFlshws()); // 流水号位数
        String qz = nowCheckType.getFqz(); // 前缀

        String nowYear = DateConversionUtils.DateToYear(new Date()); // 当前年份

        String qzReportNo = qz + nowYear; // 前缀+年份 编号

        // 按前缀+年份查询
        List<SpcySqsxBasic> reportList = spcySqsxBaiscService.list(new LambdaQueryWrapper<SpcySqsxBasic>()
                .likeRight(SpcySqsxBasic::getFpdbh, qzReportNo)
                .isNotNull(SpcySqsxBasic::getFpdbh)
                .eq(SpcySqsxBasic::getFywflcode,fywflcode));

        if (CollectionUtils.isNotEmpty(reportList)) { // 不为空
            // 获取报告编号
            List<String> reportNoList = new ArrayList<>(reportList.stream().map(SpcySqsxBasic::getFpdbh).collect(Collectors.toList()));

            // 对评定编号排序
            List<String> DescReportNoList = reportNoList.stream().sorted(Collections.reverseOrder()).collect(Collectors.toList());

            String firstReportNo = DescReportNoList.get(0); // 取最大的一个值
            int length = firstReportNo.length();
            if (length>lshws){
                String substring = firstReportNo.substring(length - lshws);

                int jqs = Integer.valueOf(substring); // 截取处理的数
                int newhjqs = jqs + 1; // 对截取处理的数+1
                String newJqsStr = String.valueOf(newhjqs); // 新字符串转字符串
                int length1 = newJqsStr.length(); // 新字符串长度

                if (lshws>length1){ // 流水号数>新字符串长度
                    int j = lshws - length1;
                    String lws = "";
                    for (int n = 0; n<j; n++){
                        lws += "0";
                    }
                    returnReportNo = qzReportNo + lws + newhjqs;
                }else if (lshws == length1){ // 长度相等
                    returnReportNo = qzReportNo + newJqsStr;
                }
            }

        }else { // 为空
            String lwz = ""; // 0的个数
            for (int i = 1; i<lshws; i++){
                lwz += "0";
            }
            qzReportNo += lwz + "1";
            returnReportNo = qzReportNo;
        }

        map.put("fpdbh",returnReportNo);

        return HttpResult.ok(map);
    }


    /**
     * 移送函编号
     */
    @Log(title = "自动移送函编号-通过业务分类")
    @ApiOperation(value = "自动移送函编号-通过业务分类")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "fywflcode",value = "业务分类编码",required = true)
    })
    @GetMapping(value = "/autoYshbhBySqsxId")
    public HttpResult<?> autoYshbhBySqsxId(@RequestParam(value = "fywflcode",defaultValue = "")String fywflcode,
                                           @RequestParam(value = "sqsxid",defaultValue = "")String sqsxid){
        if (StringUtils.isNotBlank(sqsxid)){
            fywflcode = spcySqsxBaiscService.getYwflCodeBySqsxId(sqsxid);
        }else {
            if (StringUtils.isBlank(fywflcode)) {
                return HttpResult.error("业务分类/事项参数为空,请联系管理员！");
            }
        }

        Map map = new HashMap();

        String baseYwfl = fywflcode;
        if (baseYwfl.equals(SpcyConstant.YWFL_CODE_YPZCLC)){
            baseYwfl = SpcyConstant.YWFL_CODE_YPZC;
        }

        List<SpcyRsBhgz> bghzTypeList = spcyRsBhgzService.list(new LambdaQueryWrapper<SpcyRsBhgz>()
                .eq(SpcyRsBhgz::getFywflcode, baseYwfl)
                .eq(SpcyRsBhgz::getFtype1, BhgzConstant.YSHBH));

        if (CollectionUtils.isEmpty(bghzTypeList)){
            return HttpResult.error("没有配置对应的检查类型，请先配制参数");
        }
        String returnReportNo = "";

        SpcyRsBhgz nowCheckType = bghzTypeList.get(0);
//        int lshws = Integer.valueOf(nowCheckType.getFlshws()); // 流水号位数
        String qz = nowCheckType.getFqz(); // 前缀

        String nowYear = DateConversionUtils.DateToYear(new Date()); // 当前年份

//        String qzReportNo = qz + "〔" +nowYear + "〕"; // 前缀+年份 编号
        String qzReportNo = qz + BhgzConstant.zkh + nowYear + BhgzConstant.ykh; // 前缀+年份 编号

        // 按前缀+年份查询
        List<SpcySqsxBasic> reportList = spcySqsxBaiscService.list(new LambdaQueryWrapper<SpcySqsxBasic>()
                .likeRight(SpcySqsxBasic::getFyshbh, qzReportNo)
                .isNotNull(SpcySqsxBasic::getFyshbh)
                .eq(SpcySqsxBasic::getFywflcode,fywflcode));

        if (CollectionUtils.isNotEmpty(reportList)) { // 不为空
            // 获取移送函编号
            List<String> reportNoList = new ArrayList<>(reportList.stream().map(SpcySqsxBasic::getFyshbh).collect(Collectors.toList()));

            // 对移送函编号排序
//            List<String> DescReportNoList = reportNoList.stream().sorted(Collections.reverseOrder()).collect(Collectors.toList());
            SortUtils.StringNumberSortDesc(reportNoList);

            String firstReportNo = reportNoList.get(0); // 取最大的一个值
//            int length = firstReportNo.length();
            // 桂食药审查药生函〔2020〕20号
//            String number = StringPatternUtils.getStringBetweenTwoChars(firstReportNo, '〕', '号');
            String number = StringPatternUtils.getStringBetweenTwoChars(firstReportNo, BhgzConstant.ykh, BhgzConstant.jwzf);
            if (StringUtils.isNotBlank(number)) {
                int jqs = Integer.valueOf(number.trim()); // 截取处理的数
                int newhjqs = jqs + 1; // 对截取处理的数+1
                String newJqs = String.valueOf(newhjqs);
                qzReportNo += newJqs + BhgzConstant.jwzf;
                returnReportNo = qzReportNo;
            }else {
                qzReportNo += "1" + BhgzConstant.jwzf;
                returnReportNo = qzReportNo;
            }
        }else { // 为空
            qzReportNo += "1" + BhgzConstant.jwzf;
            returnReportNo = qzReportNo;
        }

        map.put("fyshbh",returnReportNo);

        return HttpResult.ok(map);
    }

    /**
     * 补正编号
     */
    /*@Log(title = "自动补正编号-通过业务分类")
    @ApiOperation(value = "自动补正编号-通过业务分类")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "fywflcode",value = "业务分类编码",required = true)
    })*/
    @GetMapping(value = "/autoBzbhBySqsxId")
    public HttpResult<?> autoBzbhBySqsxId(@RequestParam(value = "fywflcode",defaultValue = "")String fywflcode,
                                          @RequestParam(value = "sqsxid",defaultValue = "")String sqsxid){

        if (StringUtils.isNotBlank(sqsxid)){
            fywflcode = spcySqsxBaiscService.getYwflCodeBySqsxId(sqsxid);
        }else {
            if (StringUtils.isBlank(fywflcode)) {
                return HttpResult.error("业务分类/事项参数为空,请联系管理员！");
            }
        }

        Map map = new HashMap();

        String baseYwfl = fywflcode;
        if (baseYwfl.equals(SpcyConstant.YWFL_CODE_YPZCLC)){
            baseYwfl = SpcyConstant.YWFL_CODE_YPZC;
        }

        List<SpcyRsBhgz> bghzTypeList = spcyRsBhgzService.list(new LambdaQueryWrapper<SpcyRsBhgz>()
                .eq(SpcyRsBhgz::getFywflcode, baseYwfl)
                .eq(SpcyRsBhgz::getFtype1, BhgzConstant.BQBZBH));

        if (CollectionUtils.isEmpty(bghzTypeList)){
            return HttpResult.error("没有配置对应的检查类型，请先配制参数");
        }

        String returnReportNo = "";

        /*SpcyRsBhgz nowCheckType = bghzTypeList.get(0);
        String qz = nowCheckType.getFqz(); // 前缀

        String nowYear = DateConversionUtils.DateToYear(new Date()); // 当前年份

        String qzReportNo = qz + BhgzConstant.zkh +nowYear + BhgzConstant.ykh; // 前缀+年份 编号*/

        /*// 按前缀+年份查询
        List<SpcySqsxBasic> reportList = spcySqsxBaiscService.list(new LambdaQueryWrapper<SpcySqsxBasic>()
                .likeRight(SpcySqsxBasic::getFbqbzbh, qzReportNo)
                .isNotNull(SpcySqsxBasic::getFbqbzbh)
                .eq(SpcySqsxBasic::getFywflcode,fywflcode));

        if (CollectionUtils.isNotEmpty(reportList)) { // 不为空
            // 获取移送函编号
            List<String> reportNoList = new ArrayList<>(reportList.stream().map(SpcySqsxBasic::getFbqbzbh).collect(Collectors.toList()));

            // 对移送函编号排序
//            List<String> DescReportNoList = reportNoList.stream().sorted(Collections.reverseOrder()).collect(Collectors.toList());
            SortUtils.StringNumberSortDesc(reportNoList);

            String firstReportNo = reportNoList.get(0); // 取最大的一个值
//            int length = firstReportNo.length();
            // 桂食药审查药生函〔2020〕20号
            String number = StringPatternUtils.getStringBetweenTwoChars(firstReportNo, BhgzConstant.ykh, BhgzConstant.jwzf);
            if (StringUtils.isNotBlank(number)) {
                int jqs = Integer.valueOf(number.trim()); // 截取处理的数
                int newhjqs = jqs + 1; // 对截取处理的数+1
                String newJqs = String.valueOf(newhjqs);
                qzReportNo += newJqs + BhgzConstant.jwzf;
                returnReportNo = qzReportNo;
            }else {
                qzReportNo += "1" + BhgzConstant.jwzf;
                returnReportNo = qzReportNo;
            }
        }else { // 为空
            qzReportNo += "1" + BhgzConstant.jwzf;
            returnReportNo = qzReportNo;
        }*/

        map.put("fbqbzbh",returnReportNo);

        return HttpResult.ok(map);
    }

}
